package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Transactional//事务注解,涉及到多个表的操作时，需要加上该注解
    public void addDish(DishDTO dto) {
        //构造菜品基本信息路径，将其存入dish表
        Dish dish = new Dish();
        //拷贝属性值
        BeanUtils.copyProperties(dto, dish);
        //调用mapper保存
        dishMapper.insert(dish);
        log.info("dishId:{}", dish.getId());
        //构造菜品口味裂变数据将其存入dish_flavor表
        List<DishFlavor> dishFlavorList = dto.getFlavors();
        if (dishFlavorList!=null&&dishFlavorList.size()>0)
        {
            //关联菜品id
            dishFlavorList.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
            //调用mapper保存,批量保存
            dishFlavorMapper.insertBatch(dishFlavorList);
        }

    }

    @Override
    public PageResult pageDishList(DishPageQueryDTO dto) {
        //设置分页参数
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //调用mapper查询
        Page<DishVO> page = dishMapper.pageDishList(dto);
        //封装pageResult对象并返回
        return new PageResult(page.getTotal(), page.getResult());


    }

    @Transactional//事务注解,涉及到多个表的操作时，需要加上该注解
    public void deleteDish(List<Long> ids) {
        //1.删除菜品之前，需要判断菜品是否起售，如果起售，则不能删除
        ids.forEach(id->{
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == 1)
            {throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);}

        });
        //2.需要判断菜品是否被套餐关联，关联了也不允许删除
        Integer count = setmealDishMapper.counDishByDishId(ids);
        if (count > 0)
        {throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);}
        //3.删除菜品基本信息dish
        dishMapper.deleteBatch(ids);
        //4.删除菜品口味裂变信息dish_flavor
        dishFlavorMapper.deleteBatch(ids);
    }

    @Override
    public DishVO getById(Long id) {
        DishVO dishVO = new DishVO();
        //根据id查询菜品基本信息
        Dish dish = dishMapper.selectById(id);
        BeanUtils.copyProperties(dish, dishVO);
        //根据id查询菜品口味裂变信息
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(dishFlavors);
        //构造vo对象并返回
        return dishVO;
    }

    @Transactional//事务注解,涉及到多个表的操作时，需要加上该注解
    public void update(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.update(dish);
        //更新菜品口味裂变信息
        //先删除原有数据
        dishFlavorMapper.deleteByDishId(dto.getId());
        //关联菜品id
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && flavors.size() > 0)
        {
            flavors.forEach(flavor -> {
               flavor.setDishId(dto.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 菜品起售、停售
     *
     * @param status  菜品状态：1为起售，0为停售
     * @param id      菜品 id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        // 构建只含 id 和 status 的对象，用于更新
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();

        // 调用 Mapper 更新数据库
        dishMapper.updateStatus(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listBy(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
